package com.simafei.flow.core.api.impl;

import com.simafei.flow.core.api.TemplateEngine;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author fengpengju
 */
public class TemplateEngineImpl implements TemplateEngine {

    public static final Pattern PATTERN = Pattern.compile("\\$\\{(.+?)\\}");

    @Override
    public String render(String template, Map<String, Object> params) {
        Matcher matcher = PATTERN.matcher(template);
        StringBuilder sb = new StringBuilder();

        while (matcher.find()) {
            String key = matcher.group(1);
            String replacement = (String) params.get(key);
            if (replacement == null) {
                continue;
            }
            matcher.appendReplacement(sb, replacement);
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

}
